package com.ticketbooking.service.impl;

import com.ticketbooking.entity.UserInfEntity;
import com.ticketbooking.service.IUserInfDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Types;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserInfDaoImpl implements IUserInfDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserInfEntity getUserInfById(String userid) {
        String sql = "select * from userinf u where u.userid = ?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[]{userid},new int[]{Types.VARCHAR});
        return getUserInf(list);

    }

    @Override
    public UserInfEntity getUserInfByUsername(String username) {
        String sql = "select * from userinf u where u.username = ?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[]{username},new int[]{Types.VARCHAR});
        return getUserInf(list);
    }
    @Override
    public List getAllUserInf() {
        String sql = "select * from userinf ";
        return jdbcTemplate.queryForList(sql);
    }

    @Override
    public void addAllUserInf(UserInfEntity userinf) {
        String sql = "insert into userinf(userid,username,realname,useradd,useremail,userphone,usercard) values (?,?,?,?,?,?,?)";
        Object args[] = {userinf.getUserid(),userinf.getUsername(),userinf.getRealname(),userinf.getUseradd(),userinf.getUseremail(),userinf.getUserphone(),userinf.getUseradd()};
        int[] argTypes = {Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
        jdbcTemplate.update(sql,args,argTypes);

    }

    private UserInfEntity getUserInf(List<Map<String, Object>> userinfList) {
        UserInfEntity userinf = new UserInfEntity();
        if(userinfList.size()>0){
            Map<String, Object> map = userinfList.get(0);
            userinf.setRealname((String)map.get("realname"));
            userinf.setUserid((String)map.get("userid"));
            userinf.setUserphone((String)map.get("userphone"));
            userinf.setUseradd((String)map.get("useradd"));
            userinf.setUsercard((String)map.get("usercard"));
            userinf.setUseremail((String)map.get("useremail"));
            userinf.setUsername((String)map.get("username"));}
        return userinf;
    }
}
